package com.fengxu.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Set;

/**
*@Description 群聊服务器
*@Author 风珝
*@Date 2020/12/3 13:19
*@Version 1.0.0
*/
public class GroupChatServer {
    // 用户监听用户的网络通道
    private ServerSocketChannel listenChannel;
    // 通道选择器
    private Selector selector;
    // 绑定的本地端口号
    private final int PORT = 6666;

    public GroupChatServer(){
        try {
            listenChannel = ServerSocketChannel.open();
            selector = Selector.open();
            listenChannel.bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务器开始监听6666端口...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run(){
        // 监听通道中是否有事件发生
        try {
            while (true){
                int count = selector.select(2000);
                if(count == 0){
                    continue;
                }
                Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                while (keyIterator.hasNext()){
                    SelectionKey selectionKey = keyIterator.next();
                    // 当有用户连接时
                    if(selectionKey.isAcceptable()){
                        SocketChannel clientChannel = listenChannel.accept();
                        acceptClient(clientChannel);
                    }
                    // 当用户发送消息时
                    if(selectionKey.isReadable()){
                        // 接受并转发消息
                        receiveAndSendMessage(selectionKey);
                    }
                    keyIterator.remove();
                }
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                listenChannel.close();
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("发生异常服务器，强制关闭");
        }
    }

    // 接受新连接的用户
    private void acceptClient(SocketChannel clientChannel){
        try {
            clientChannel.configureBlocking(false);
            // 设置连接进来的影用户关联read事件并设置了他初始化的时候附加了一个ByteBuffer对象
            // 该附加对象可以通过selectionKey.attachment()得到
            clientChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
            System.out.println(clientChannel.getRemoteAddress()+"用户上线!");
        } catch (IOException e) {
            System.out.println("接受客户端异常!!!");
        }
    }

    // 接受消息并转发
    private void receiveAndSendMessage(SelectionKey selectionKey){
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
            byteBuffer.clear();
            int len = channel.read(byteBuffer);
            String msg = new String(byteBuffer.array(),0,len);
            System.out.println("服务器转发用户消息:"+ msg);
            // 将该消息转发值所有客户端
            for (SelectionKey key : selector.keys()) {
                SelectableChannel clientChannel = key.channel();
                // 排除掉非用户的通道
                if(clientChannel instanceof SocketChannel){
                    // 将信息转发至所有用户
                    ((SocketChannel)clientChannel).write(ByteBuffer.wrap(msg.getBytes()));
                }
            }
        } catch (IOException e) {
            try {
                System.out.println("发送消息异常,"+channel.getRemoteAddress().toString()+"用户离线");
                // 取消注册
                selectionKey.cancel();
                // 关闭通道
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

}
